package org.linlinjava.litemall.admin.web;

import com.github.pagehelper.Page;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.dto.BrandMsg;
import org.linlinjava.litemall.admin.dto.BrandQualify;
import org.linlinjava.litemall.admin.service.AdminContactService;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 虽然写的是品牌管理   但实际上应该是商户的管理
 */
@RestController
@RequestMapping("/admin/brand")
@Validated
public class AdminBrandController {
    private final Log logger = LogFactory.getLog(AdminBrandController.class);

    @Autowired
    private LitemallBrandService brandService;
    @Autowired
    private LitemallQualificationService qualificationService;
    @Autowired
    private LitemallBrandQualificationService brandQualificationService;
    @Autowired
    private LitemallBrandInfoService brandInfoService;
    @Autowired
    private LitemallConstantService constantService;
    @Autowired
    private AdminContactService adminContactService;
    @Autowired
    private LitemallServiceService serviceService;


    @RequiresPermissions("admin:brand:list")
    @RequiresPermissionsDesc(menu = {"商场管理", "品牌管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String id, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        BrandMsg msg = new BrandMsg();
        List<LitemallBrand> brandList = brandService.querySelective(id, name, page, limit, sort, order);
        Page listPage = (Page) brandList;
        long total = listPage.getTotal();
        List<BrandQualify> brandQualifies =new ArrayList<>();
        for (LitemallBrand brand : brandList) {
            BrandQualify brandQualify = new BrandQualify();
            List<Integer> list = new ArrayList<>();
            List<LitemallBrandQualification> byQIdAndBrandId = brandQualificationService.findByBrandIdAndHas(brand.getId());
            for (LitemallBrandQualification brandQualification : byQIdAndBrandId) {
                list.add(brandQualification.getQualificationId());
            }
            brandQualify.setBrand(brand);
            brandQualify.setList(list);
            brandQualifies.add(brandQualify);
        }
        msg.setBrandQualifies(brandQualifies);
        msg.setTotal(total);
        return ResponseUtil.ok(msg);
    }
    private Object validate(LitemallBrand brand) {
        String name = brand.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }

        return null;
    }

    @RequiresPermissions("admin:brand:create")
    @RequiresPermissionsDesc(menu = {"商场管理", "品牌管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody BrandMsg brandMsg) throws Exception {
        LitemallBrand brand = brandMsg.getBrand();
        List<Integer> list = brandMsg.getList();
        Object error = validate(brand);
        if (error != null) {
            return error;
        }
        String password = "123456";
        if (!StringUtils.isEmpty(password)) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode(password);
            brand.setPassword(encodedPassword);
        }
        List<LitemallBrand> brands = brandService.queryByUsername(brand.getName());
        List<LitemallBrand> brands1 = brandService.queryByDomain(brand.getDomain());
        List<LitemallBrand> brands2 = brandService.queryByName(brand.getName());
        if(brands!=null&&brands.size()>0){
            return ResponseUtil.fail(-1,"用户名已存在");
        }else if(brands1!=null&&brands1.size()>0){
            return ResponseUtil.fail(-1,"域名已存在");
        }else if(brands2!=null&&brands2.size()>0){
            return ResponseUtil.fail(-1,"公司名已存在");
        }else{
            brandService.add(brand);
            List<LitemallQualification> litemallQualifications = qualificationService.querySelective(1, 100);
            for (LitemallQualification litemallQualification : litemallQualifications) {
                LitemallBrandQualification brandQualification = new LitemallBrandQualification();
                brandQualification.setBrandId(brand.getId());
                brandQualification.setQualificationId(litemallQualification.getId());
                brandQualification.setIsHas(0);
                brandQualificationService.add(brandQualification);
            }
            for (Integer integer : list) {
                List<LitemallBrandQualification> byQIdAndBrandId = brandQualificationService.findByQIdAndBrandId(integer, brand.getId());
                byQIdAndBrandId.get(0).setIsHas(1);
                brandQualificationService.updateById(byQIdAndBrandId.get(0));
            }
            LitemallBrandInfo brandInfo = new LitemallBrandInfo();
            brandInfo.setBrandId(brand.getId());
            brandInfo.setHomepage(brand.getDomain());
            brandInfo.setBrandName(brand.getName());
            serviceService.insert(brand);
            brandInfoService.add(brandInfo);
            return ResponseUtil.ok(brand);
        }
    }
    @RequiresPermissions("admin:brand:read")
    @RequiresPermissionsDesc(menu = {"商场管理", "品牌管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        BrandMsg msg = new BrandMsg();
        LitemallBrand brand = brandService.findById(id);
        msg.setBrand(brand);
        return ResponseUtil.ok(msg);
    }

    @RequiresPermissions("admin:brand:update")
    @RequiresPermissionsDesc(menu = {"商场管理", "品牌管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody BrandMsg brandMsg) {
        List<Integer> list = brandMsg.getList();
        LitemallBrand brand = brandMsg.getBrand();
        Object error = validate(brand);
        if (error != null) {
            return error;
        }
        String password = brand.getPassword();
        if (!StringUtils.isEmpty(password)) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode(password);
            brand.setPassword(encodedPassword);
        }
        if (brandService.updateById(brand) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        List<LitemallBrandQualification> byId = brandQualificationService.findByBrandId(brand.getId());
        for (LitemallBrandQualification brandQualification : byId) {
            brandQualification.setIsHas(0);
            brandQualificationService.updateById(brandQualification);
        }
        for (Integer integer : list) {
            List<LitemallBrandQualification> byQIdAndBrandId = brandQualificationService.findByQIdAndBrandId(integer, brand.getId());
            byQIdAndBrandId.get(0).setIsHas(1);
            brandQualificationService.updateById(byQIdAndBrandId.get(0));
        }
        LitemallBrandInfo brandInfo = brandInfoService.getInfoByBrandId(brand.getId());
        brandInfo.setHomepage(brand.getDomain());
        brandInfo.setBrandName(brand.getName());
        serviceService.update(brand);
        brandInfoService.updateByBrandId(brandInfo);
        return ResponseUtil.ok(brand);
    }
    @RequiresPermissions("admin:brand:delete")
    @RequiresPermissionsDesc(menu = {"商场管理", "品牌管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallBrand brand) {
        Integer id = brand.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        brandService.deleteById(id);
        brandQualificationService.deleteByBrandId(id);
        brandInfoService.deleteById(id);
        serviceService.deletedByBrand(id);
        return ResponseUtil.ok();
    }
    @RequiresPermissions("admin:brand:listCons")
    @PostMapping("/listCons")
    public Object listCons() {
        List<LitemallConstant> allConstant = constantService.getAllConstant();
        return ResponseUtil.ok(allConstant);
    }

    @GetMapping("/listConcact")
    public Object listPic(){
        LitemallContact litemallContact = adminContactService.findAll();
        return ResponseUtil.ok( litemallContact);
    }
    @RequiresPermissions("admin:brand:addConcact")
    @PostMapping("/addConcact")
    public Object addPic(@RequestBody LitemallContact litemallContact){
        adminContactService.addContact(litemallContact);
        return ResponseUtil.ok(litemallContact);
    }
    @RequiresPermissions("admin:brand:updateConcact")
    @PostMapping("updateConcact")
    public Object updatePic(@RequestBody LitemallContact litemallContact){
        adminContactService.updateContact(litemallContact);
        return ResponseUtil.ok(litemallContact);
    }

}
